import React, { useEffect, useState } from 'react';
import { Modal as AntdModal, Form, Select, message, Input, Radio, Upload, Button } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import { checkStaffPhone, checkStaffIdNumber, saveStaff, deleteFile } from '@/services/staffManage';
import { getToken } from '@/utils/utils';

const Modal = ({
  modalVisible,
  modalTitle,
  updateModalVisible,
  staffInfoModal,
  staffDepartmentList,
  Refresh,
  updateAid,
}) => {
  const [form] = Form.useForm();
  const layout = {
    labelCol: { span: 6 },
    wrapperCol: { span: 18 },
  };
  const [isSubmit1, setISubmit1] = useState(true);
  const [isSubmit2, setISubmit2] = useState(true);
  const [fileList, setFileList] = useState(); //保存上传的文件
  const [fileData, setFileData] = useState();

  // 给表单赋值
  useEffect(() => {
    if (staffInfoModal && modalVisible) {
      const data = [];
      for (var i = 0; i < staffInfoModal.list.length; i++) {
        data.push({ label: staffInfoModal.list[i].name, value: staffInfoModal.list[i].aid });
      }
      if (staffInfoModal.file.enclosureName === null) {
        setFileData(undefined);
      } else {
        setFileData([
          { name: staffInfoModal.file.enclosureName, uid: staffInfoModal.file.enclosureId },
        ]);
      }

      form.setFieldsValue({
        ...staffInfoModal,
        list: data,
      });
    } else {
      form.resetFields();
    }
  }, [modalVisible]);

  // 确定提交表单
  const actionHandle = () => {
    if (isSubmit1 && isSubmit2) {
      form.submit();
    } else {
      message.error('身份证号码或手机号重复!!!');
    }
  };

  //取消提交表单
  const handleCancel = () => {
    updateModalVisible();
  };

  // 发送请求
  const onFinish = async (values) => {
    const newArray = new Array();
    values.list.map((item) => {
      newArray.push(item.value);
    });
    const { idNumber, sex, name, password, phone } = values;
    const params = {
      idNumber,
      sex,
      name,
      password,
      phone,
      departmentList: newArray,
      aid: updateAid,
      enclosureId: fileList === undefined ? undefined : fileList[0]?.data,
    };
    await saveStaff(params);
    setISubmit1(true);
    setISubmit2(true);
    updateModalVisible();
    Refresh();
  };

  //校验相同手机的其他员工是否存在
  const checkPhone = async (phone) => {
    const checkPhoneList = await checkStaffPhone({ phone });
    if (checkPhoneList && checkPhoneList.isExists) {
      const data = [];
      for (var i = 0; i < checkPhoneList.list.list.length; i++) {
        data.push({
          label: checkPhoneList.list.list[i].name,
          value: checkPhoneList.list.list[i].aid,
        });
      }
      form.setFieldsValue({
        ...checkPhoneList.list,
        list: data,
      });
      setISubmit1(false);
      setISubmit2(false);
    } else {
      setISubmit1(true);
    }
  };

  //校验相同身份证号的其他员工是否存在
  const checkIdNumber = async (idNumber) => {
    const checkIdNumberList = await checkStaffIdNumber({ idNumber });
    if (checkIdNumberList && checkIdNumberList.isExists) {
      const data = [];
      for (var i = 0; i < checkIdNumberList.list.list.length; i++) {
        data.push({
          label: checkIdNumberList.list.list[i].name,
          value: checkIdNumberList.list.list[i].aid,
        });
      }
      form.setFieldsValue({
        ...checkIdNumberList.list,
        list: data,
      });
      setISubmit1(false);
      setISubmit2(false);
    } else {
      setISubmit2(true);
    }
  };

  //上传文件
  const props = {
    name: 'file',
    action: 'http://localhost:8806/upload',
    headers: {
      token: getToken(),
    },
    multiple: true, //支持多个文件
    showUploadList: true, //展示文件列表
    beforeUpload: (file) => {
      setFileData([{ name: file.name, uid: file.uid }]);
    },

    onChange(info) {
      const list = [];
      if (info.file.status === 'done') {
        info.fileList.map((item) => {
          list.push({ data: item.response.data.data });
        });
        setFileList(list);
        message.success(`${info.file.name} 文件上传成功`);
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} 文件上传失败`);
      }
    },
    onRemove(file) {
      deleteFile({ enclosureId: file.uid });
      setFileList(undefined);
      setFileData(undefined);
      message.success('删除成功');
      return true;
    },
  };

  return (
    <div>
      <AntdModal
        title={modalTitle}
        visible={modalVisible}
        onOk={actionHandle}
        onCancel={handleCancel}
        forceRender={true} //强制渲染modal
        maskClosable={false} //点击modal外面的界面不关闭
      >
        <Form {...layout} form={form} onFinish={onFinish} validateTrigger="onBlur">
          <Form.Item
            key="1"
            label="姓名："
            name="name"
            rules={[
              {
                required: true,
                message: '请输入姓名',
              },
              {
                pattern: /^[\s\S]{1,16}$/,
                message: '姓名格式错误！！',
              },
            ]}
          >
            <Input placeholder="请输入" />
          </Form.Item>
          <Form.Item key="2" label="性别：" name="sex" required="true">
            <Radio.Group>
              <Radio value={true}>男</Radio>
              <Radio value={false}>女</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item
            key="3"
            label="身份证号码："
            name="idNumber"
            rules={[
              {
                required: true,
                message: '请输入身份证号！',
              },
              {
                pattern:
                  /^[1-9]\d{5}(18|19|20|(3\d))\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/,
                message: '身份证号码格式错误！！',
              },
            ]}
            onBlur={(event) => {
              checkIdNumber(event.target.value);
            }}
          >
            <Input placeholder="请输入" />
          </Form.Item>
          <Form.Item
            key="4"
            label="密码："
            name="password"
            rules={[
              {
                required: true,
                message: '请输入密码',
              },
              {
                pattern: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$/,
                message: '密码格式错误！！',
              },
            ]}
          >
            <Input.Password placeholder="请输入" />
          </Form.Item>
          <Form.Item
            key="5"
            label="手机号码："
            name="phone"
            rules={[
              {
                required: true,
                message: '请输用户账号!',
              },
              {
                pattern: /^1[3-9][0-9]{9}$/,
                message: '手机号格式错误！！！',
              },
            ]}
            onBlur={(event) => {
              checkPhone(event.target.value);
            }}
          >
            <Input placeholder="请输入" />
          </Form.Item>
          <Form.Item
            label="部门："
            name="list"
            key="6"
            rules={[
              {
                required: true,
                message: '请选择部门！',
              },
            ]}
          >
            <Select placeholder="请选择" mode="multiple" allowClear={true} labelInValue={true}>
              {staffDepartmentList.map((field) => {
                return (
                  <Select.Option key={field.aid} value={field.aid}>
                    {field.name}
                  </Select.Option>
                );
              })}
            </Select>
          </Form.Item>
          <Form.Item key="7" label="上传附件：" name="fileList">
            <Upload {...props} fileList={fileData} maxCount={1}>
              <Button icon={<UploadOutlined />}>Click to Upload</Button>
            </Upload>
          </Form.Item>
        </Form>
      </AntdModal>
    </div>
  );
};

export default Modal;
